<?php

declare(strict_types=1);

namespace app\controller\system\notify;

use app\BaseController;
use app\service\factory\ResponseFactory;
use app\service\notify\MessageService;
use app\service\notify\RecordService;
use app\validate\notify\MessageValidate;
use InvalidArgumentException;
use think\Response;
use Throwable;

class Message extends BaseController
{
    public function save(MessageService $messageService, RecordService $recordService): Response
    {
        try {
            $payload = $this->request->post();

            $this->validate($payload, MessageValidate::class . '.create');

            $message = $messageService->create($payload);
            $formatted = $recordService->format($message);

            return json(ResponseFactory::success($formatted, '通知已创建'));
        } catch (InvalidArgumentException $e) {
            return json(ResponseFactory::error($e->getMessage(), 422));
        } catch (Throwable $e) {
            return json(ResponseFactory::error($e->getMessage(), $e->getCode() ?: 500));
        }
    }
}
